<template>
  <BasicDrawer v-bind="$attrs" :showFooter="false" @register="registerDrawer" width="60%">
    <template #title>
      <div class="flex items-center space-x-3">
        <Icon icon="ant-design:apartment-outlined" :size="22" />
        <div class="flex flex-col">
          <span class="text-base font-semibold">{{ groupRecord.name || '设备组详情' }}</span>
          <span class="text-sm text-gray-500">设备组详情</span>
        </div>
      </div>
    </template>
    <div class="group-detail">
      <section class="group-detail__summary">
        <div class="group-detail__actions">
          <a-button type="primary" @click="handleEditGroup">
            <Icon icon="ant-design:edit-outlined" /> 编辑设备组
          </a-button>
          <a-button danger @click="handleDeleteGroup"> <Icon icon="ant-design:delete-outlined" /> 删除设备组 </a-button>
        </div>
        <Row :gutter="16" class="mt-4">
          <Col :span="6">
            <div class="summary-item">
              <div class="summary-item__label">终端数量</div>
              <div class="summary-item__value">{{ groupRecord.deviceCount ?? '-' }}</div>
            </div>
          </Col>
          <Col :span="6">
            <div class="summary-item">
              <div class="summary-item__label">创建人</div>
              <div class="summary-item__value">{{ creatorName }}</div>
            </div>
          </Col>
          <Col :span="6">
            <div class="summary-item">
              <div class="summary-item__label">创建时间</div>
              <div class="summary-item__value">{{ createdTime }}</div>
            </div>
          </Col>
          <Col :span="6">
            <div class="summary-item">
              <div class="summary-item__label">IP 地址</div>
              <div class="summary-item__value">{{ ipAddress }}</div>
            </div>
          </Col>
        </Row>
        <div class="summary-item mt-4">
          <div class="summary-item__label">状态</div>
          <Tag :color="statusTag.color">{{ statusTag.text }}</Tag>
        </div>
      </section>

      <section class="group-detail__description">
        <div class="section-header">分组描述</div>
        <div class="section-body">{{ groupRecord.description || '暂无描述' }}</div>
      </section>

      <section class="group-detail__devices">
        <div class="section-header flex justify-between items-center">
          <span>设备列表 ({{ deviceCountText }})</span>
          <div>
            <a-button @click="handleReloadGroup"> <Icon icon="ant-design:reload-outlined" /> 刷新 </a-button>
          </div>
        </div>
        <div v-if="deviceList.length > 0" class="device-list">
          <div v-for="device in deviceList" :key="device.id" class="device-item">
            <div class="device-item__name">{{ device.deviceName || '-' }}</div>
            <div class="device-item__actions">
              <a-button type="link" size="small" @click="handleConfigureTag(device)">配置标签</a-button>
              <a-button type="link" danger size="small" @click="handleRemoveDevice(device)">移除</a-button>
            </div>
          </div>
        </div>
        <div v-else class="empty-devices">
          <Icon icon="ant-design:inbox-outlined" :size="48" class="empty-icon" />
          <div class="empty-text">暂无设备</div>
        </div>
      </section>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsTbGroupDetail">
  import { computed, ref } from 'vue';
  import { Icon } from '/@/components/Icon';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Tag, Row, Col, Modal } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';
  import { getDeviceGroupById, removeDeviceFromGroup, type DeviceInGroup } from '/@/api/tb/group';
  import type { Recordable } from '/@/types';

  interface GroupRecord {
    id?: { id: string; entityType?: string } | string;
    name?: string;
    description?: string;
    deviceCount?: number;
    createdTime?: number;
    additionalInfo?: Record<string, any>;
    devices?: DeviceInGroup[];
    [key: string]: any;
  }

  const emit = defineEmits(['register', 'edit', 'delete', 'manageDevices']);

  const groupRecord = ref<GroupRecord>({});
  const deviceList = ref<DeviceInGroup[]>([]);
  const { showMessage } = useMessage();

  const creatorName = computed(
    () => groupRecord.value?.additionalInfo?.createdBy || groupRecord.value.createdBy || '-',
  );
  const createdTime = computed(() =>
    groupRecord.value.createdTime ? dayjs(groupRecord.value.createdTime).format('YYYY-MM-DD HH:mm:ss') : '-',
  );
  const ipAddress = computed(() => groupRecord.value?.additionalInfo?.ipAddress || '-');
  const statusTag = computed(() => {
    const status = groupRecord.value?.additionalInfo?.status || '未知';
    const mapping: Record<string, { text: string; color: string }> = {
      启用: { text: '启用', color: 'success' },
      停用: { text: '停用', color: 'default' },
      未知: { text: '未知', color: 'warning' },
    };
    return mapping[status] || { text: status, color: 'processing' };
  });
  const deviceCountText = computed(() => deviceList.value?.length ?? groupRecord.value.deviceCount ?? 0);

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (record: GroupRecord) => {
    try {
      setDrawerProps({ loading: true });

      // 获取设备分组详情信息
      const deviceGroupId =
        record?.id && typeof record.id === 'object' ? record.id.id : (record?.id as string | undefined);
      if (deviceGroupId) {
        try {
          const detailData = await getDeviceGroupById(deviceGroupId);
          groupRecord.value = { ...detailData };
          deviceList.value = detailData.devices || [];
        } catch (error: any) {
          showMessage(`获取设备分组详情失败: ${error?.message || '未知错误'}`, 'error');
          // 如果获取详情失败，使用传入的记录数据
          groupRecord.value = { ...record };
          deviceList.value = record.devices || [];
        }
      } else {
        groupRecord.value = { ...record };
        deviceList.value = record.devices || [];
      }
    } finally {
      setDrawerProps({ loading: false });
    }
  });

  async function handleReloadGroup() {
    const deviceGroupId =
      groupRecord.value?.id && typeof groupRecord.value.id === 'object'
        ? groupRecord.value.id.id
        : (groupRecord.value?.id as string | undefined);

    if (!deviceGroupId) return;

    try {
      const detailData = await getDeviceGroupById(deviceGroupId);
      groupRecord.value = { ...detailData };
      deviceList.value = detailData.devices || [];
      showMessage('刷新成功', 'success');
    } catch (error: any) {
      showMessage(`刷新失败: ${error?.message || '未知错误'}`, 'error');
    }
  }

  function handleAddDevice() {
    emit('manageDevices', groupRecord.value);
  }

  function handleConfigureTag(record: Recordable) {
    showMessage(`配置标签功能待实现（${record?.name || '-'}）`, 'info');
  }

  function handleRemoveDevice(record: Recordable) {
    Modal.confirm({
      title: '确认移除设备',
      content: `确定要从设备组中移除设备 "${record?.deviceName || '-'}" 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const deviceGroupId =
            groupRecord.value?.id && typeof groupRecord.value.id === 'object'
              ? groupRecord.value.id.id
              : (groupRecord.value?.id as string | undefined);

          if (!deviceGroupId) {
            showMessage('设备组ID不存在', 'error');
            return;
          }

          await removeDeviceFromGroup({
            deviceGroupId,
            deviceIds: [record.id],
          });

          showMessage('设备移除成功', 'success');

          // 刷新设备列表
          await handleReloadGroup();
        } catch (error: any) {
          showMessage(`移除设备失败: ${error?.message || '未知错误'}`, 'error');
        }
      },
    });
  }

  function handleEditGroup() {
    emit('edit', groupRecord.value);
    closeDrawer();
  }

  function handleDeleteGroup() {
    emit('delete', groupRecord.value);
    closeDrawer();
  }
</script>
<style lang="less" scoped>
  .group-detail {
    padding: 12px 4px 24px;

    &__summary {
      background: #f6f9ff;
      border-radius: 8px;
      padding: 16px;

      & > .group-detail__actions {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
      }

      .summary-item {
        &__label {
          color: #8c8c8c;
          font-size: 12px;
          margin-bottom: 4px;
        }
        &__value {
          font-size: 16px;
          font-weight: 600;
        }
      }
    }

    &__description,
    &__devices {
      margin-top: 24px;
      background: #fff;
      border-radius: 8px;
      padding: 16px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
    }

    .section-header {
      font-weight: 600;
      font-size: 14px;
      margin-bottom: 12px;
    }

    .section-body {
      color: #595959;
      line-height: 1.6;
    }

    .device-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .device-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      background: #fafafa;
      border-radius: 6px;
      border: 1px solid #f0f0f0;
      transition: all 0.3s;

      &:hover {
        background: #f5f5f5;
        border-color: #d9d9d9;
      }

      &__name {
        font-size: 14px;
        color: #262626;
        font-weight: 500;
      }

      &__actions {
        display: flex;
        gap: 8px;
      }
    }

    .empty-devices {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 48px 24px;
      color: #bfbfbf;

      .empty-icon {
        margin-bottom: 16px;
        opacity: 0.5;
      }

      .empty-text {
        font-size: 14px;
        color: #8c8c8c;
      }
    }
  }
</style>
